package com.mobilesales.android.infrastructure;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.mobilesales.android.database.ClientManager;
import com.mobilesales.android.database.ParamManager;
import com.mobilesales.android.model.clients.Client;
import com.mobilesales.android.model.clients.ClientGroup;
import com.mobilesales.android.model.params.Param;
import com.mobilesales.android.services.ClientServiceClient;
import com.mobilesales.android.services.ParamServiceClient;
import com.mobilesales.android.util.LogFlags;
import com.mobilesales.android.util.Settings;

public class SyncService {

	private Context context;
	
	public SyncService(Context ctx) {
		this.context = ctx;
	}
	
	public boolean synchronize() {
		if (Settings.getSettings()==null) return false;
		boolean success = true;
		
		try {
			this.synchronizeClientGroups();
			this.synchronizeParams();
			this.synchronizeClients();
		}
		catch(Exception ex) {
			Log.i(LogFlags.RestService, ex.getMessage(), ex);
			success = false;
		}
		return success;
	}
	
	private void synchronizeParams() throws Exception {
		ParamServiceClient paramService = new ParamServiceClient(Settings.ParamService());
		ParamManager paramManager = new ParamManager(context);
		List<Param> params = paramService.getParamList();
		boolean success = true;
		if (params!=null) {
			for(Param p : params) {
				success &= paramManager.StoreParam(p);
			}
		}
		else {
			success = false;
		}
		paramManager.Close();
		if (!success)
			throw new Exception("Could not synchronize params");
	}
	
	private void synchronizeClientGroups() throws Exception {
		ClientServiceClient clientService = new ClientServiceClient(Settings.ClientService());
		ClientManager clientManager = new ClientManager(context);
		List<ClientGroup> groups = clientService.getClientGroupList();
		boolean success = true;
		if (groups!=null) {
			for(ClientGroup g : groups) {
				success &= clientManager.StoreClientGroup(g);
			}
		}
		else {
			success = false;
		}
		clientManager.Close();
		if (!success)
			throw new Exception("Could not synchronize client groups");
	}
	
	private void synchronizeClients() throws Exception {
		ClientServiceClient clientService = new ClientServiceClient(Settings.ClientService());
		List<Client> clients = clientService.getClientList();
		ClientManager clientManager = new ClientManager(context);
		boolean success = true;
		if (clients!=null) {
			for(Client c : clients)
				success &= clientManager.StoreClient(c);
		}
		else {
			success = false;
		}	
		clientManager.Close();
		if (!success)
			throw new Exception("Could not synchronize clients");
	}
	
}
